/**
 * 
 */
package com.humanmonth.framework.dao;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

/**
 * @author 林子龙
 * 
 */
public abstract class JDOTemplate<T> {
	private static Logger log = Logger.getLogger(JDOTemplate.class.getName());
	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");
	private static ThreadLocal<List<PersistenceManager>> pms = new ThreadLocal<List<PersistenceManager>>();

	
	/**
	 * 把持久管理器放在线程变量中
	 */
	private void addPm(PersistenceManager pm) {
		if (pms.get() == null) {
			pms.set(new LinkedList<PersistenceManager>());
		}
		pms.get().add(pm);
	}

	/**
	 * 关闭所次请求中的所有pm
	 */
	public static void closePm() {
		if (pms.get() == null) {
			return;
		}
		for (PersistenceManager pm : pms.get()) {
			try {
				pm.close();
			} catch (Exception e) {
				log.warning("关闭pm时出错");
				e.printStackTrace();
			}
		}
		pms.set(null);
	}

	public abstract void deal(PersistenceManager pm, List<T> result);

	public List<T> execute() {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		this.addPm(pm);
		List<T> result = new LinkedList<T>();
		this.deal(pm, result);
		return result;
	}
}
